﻿#region License

// // -------------------------------------------------------------------------------------
// // This information refers to MethodRoutingJsonHandler.cs
// // 
// // Copyright 2012 ELEN7046 Group 2
// // 
// // Last Modified on: 2012-06-10
// // 
// // Contributors:
// // 
// // Amith Sewnarain
// // Elmar Vosloo
// // Jason Thorne
// // Satish Jewan
// // 
// // Wits University 
// // School of Electrical & Information Engineering
// // Software Engineering Tools and Techniques
// // 
// // -------------------------------------------------------------------------------------
// // 
// // This file (MethodRoutingJsonHandler.cs) is part of the DishDash Event Visualization System.
// // 
// // DishDash is free software: you can redistribute it and/or modify
// // it under the terms of the GNU General Public License as published by
// // the Free Software Foundation, either version 3 of the License, or
// // (at your option) any later version.
// // 
// // DishDash is distributed in the hope that it will be useful,
// // but WITHOUT ANY WARRANTY; without even the implied warranty of
// // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// // GNU General Public License for more details.
// // 
// // You should have received a copy of the GNU General Public License
// // along with DishDash.  
// // If not, see <http://www.gnu.org/licenses/>.
// // -------------------------------------------------------------------------------------

#endregion

#region Using Directives

using System;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;

#endregion

//using MessageAPI.Core.Implementation;
//using DishDash.Common;
//using MessageAPI;

namespace Custom.Web.Extensions
{
    public abstract class MethodRoutingJsonHandler : IHttpHandler
    {
        //private long startTime;

        #region IHttpHandler Members

        /// <summary>
        ///   Enables processing of HTTP Web requests by a custom HttpHandler that implements the System.Web.IHttpHandler interface.
        /// </summary>
        /// <param name="context"> An System.Web.HttpContext object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests. </param>
        public void ProcessRequest(HttpContext context)
        {
            //Start the time for the performance event
            //StartTimer();

            var operation = GetOperationName(context);
            var method = GetHandlerMethodForOperation(operation);
            var inputType = GetInputType(method);

            var request = new byte[context.Request.InputStream.Length];
            context.Request.InputStream.Read(request, 0, request.Length);
            var json = System.Text.ASCIIEncoding.UTF8.GetString(request);

            var js = new JavaScriptSerializer();

            var inObj = js.Deserialize(json, inputType);

            try
            {
                var response = method.Invoke(this, new[] {inObj});
                context.Response.Write(js.Serialize(response));
            }
            catch (Exception e)
            {
                var errorDetails = new {Error = true, ErrorText = e.InnerException.Message};
                context.Response.StatusCode = 400;
                context.Response.StatusDescription = "Bad Request";
                context.Response.Write(js.Serialize(errorDetails));
            }

            //Create context values for performance event
            //Dictionary<string, string> contexts = new Dictionary<string, string>();
            //contexts.Add("operation", operation);
            //contexts.Add("method", method.ToString());
            //contexts.Add("inputType", inputType.ToString());

            ////Log the event
            //LogEvent("System.Web.Extensions.MethodRoutingJsonHandler.ProcessRequest", contexts);
        }

        /// <summary>
        ///   Gets a value indicating whether another request can use the System.Web.IHttpHandler instance.
        /// </summary>
        public bool IsReusable
        {
            get { return false; }
        }

        #endregion

        /// <summary>
        /// Gets the name of the operation.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        private static string GetOperationName(HttpContext context)
        {
            //Build Further Validation
            return context.Request.QueryString["Op"];
        }

        /// <summary>
        /// Gets the handler method for operation.
        /// </summary>
        /// <param name="operation">The operation.</param>
        /// <returns></returns>
        private System.Reflection.MethodInfo GetHandlerMethodForOperation(string operation)
        {
            return (from m in this.GetType().GetMethods()
                    where m.Name.ToUpperInvariant() == operation.ToUpperInvariant()
                          & m.GetParameters().Length == 1
                    select m).First();
        }

        /// <summary>
        /// Gets the type of the input.
        /// </summary>
        /// <param name="method">The method.</param>
        /// <returns></returns>
        private static Type GetInputType(System.Reflection.MethodInfo method)
        {
            return method.GetParameters()[0].ParameterType;
        }

        //private void StartTimer()
        //{
        //    startTime = DateTime.Now.Ticks;
        //}

        /// <summary>
        /// Log the a peformance event using the MessageAPI. Also stops the timer and resets it.
        /// </summary>
        /// <param name="EventDesc">The namespace and method name</param>
        /// <param name="contextvalues">The context values of the performance event</param>
        //private void LogEvent(string EventDesc, Dictionary<string, string> contextvalues)
        //{
        //    long stopTime = DateTime.Now.Ticks;
        //    long duration = (stopTime - startTime) / 10000;
        //    startTime = 0;

        //    IPerformanceInstrumentationServiceFactory performanceInstrumentationServiceFactory = new PerformanceInstrumentationServiceFactory();
        //    IPerformanceInstrumentationService performanceInstrumentationService = performanceInstrumentationServiceFactory.GetPerformanceInstrumentationService();

        //    PerformanceEvent performanceEvent = new PerformanceEvent()
        //    {
        //        Category = EventDesc,
        //        TimeStamp = DateTime.Now.Ticks,
        //        Value = duration,
        //        ContextValues = contextvalues
        //    };

        //    performanceInstrumentationService.SendEvent(performanceEvent);
        //}
    }
}